const recorderManager = wx.getRecorderManager();
Component({
	options: {
		addGlobalClass: true, // 加载组件css文件,需在app.wxss中引入组件css文件
	},
	data: {
		canSend: false,
		touchEnd: false,
		recording: false,
		callOnStart: false,
	},
	methods: {
		handleLongPress(e) {
			if (e.target.id === 'chat') {
				this.setData({
					canSend: true,
					recording: true
				});
				this.startRecording();
			}
		},
		handleTouchEnd () {
			var self = this;
			this.hideLoading();
			// 执行了onStart才执行stop,正常得操作
			if(this.data.callOnStart){
				recorderManager.stop();
				this.setData({
					callOnStart: false
				});
			}else{
				// 先执行handleTouchEnd()，后执行recorderManager.onStart()
				this.setData({
					touchEnd: true
				})
			}
		},
		startRecording() {
			wx.getSetting({
				success: (res) => {
					let auth = res.authSetting['scope.record']
					if (auth === false) { // 已申请过授权，但是用户拒绝
						wx.openSetting({
							success: function(res) {
								let auth = res.authSetting['scope.record']
								if (auth === true) {
									wx.showToast({
										title: '授权成功',
										icon: 'success',
										duration: 1500
									})
								} else {
									wx.showToast({
										title: '授权失败',
										icon: 'none',
										duration: 1500
									})
								}
							}
						})
					} else if (auth === true) { // 用户已经同意授权
						recorderManager.start();
					} else { // 第一次进来，未发起授权
						wx.authorize({
							scope: 'scope.record',
							success: () => {
								wx.showToast({
									title: '授权成功',
									icon: 'success',
									duration: 1500
								})
							}
						})
					}
				},
				fail: function() {
					wx.showToast({
						title: '授权失败',
						icon: 'none',
						duration: 1500
					})
				}
			})
		},
		hideLoading() {
			this.setData({
				recording: false
			});
		}
	},
	attached() {
		var self = this;
		recorderManager.onStart(function() {
			console.log('recorder start')
			// 先执行handleTouchEnd时才执行该段代码，并将中断录音
			if(self.data.touchEnd){
				recorderManager.stop();
				self.setData({
					touchEnd: false,
				})
			}else{
				self.setData({
					callOnStart: true
				})
			}
		});
		recorderManager.onPause(() => {
			console.log('recorder pause')
		});
		recorderManager.onStop(function(res) {
			console.log('recorder stop')
			self.hideLoading();
			if (self.data.canSend) {
				if (res.duration < 1000) {
					wx.showToast({
						title: '录音时间太短',
						icon: "none"
					});
				} else {
					self.triggerEvent('onStop', res);
				}
			}
		});
		recorderManager.onError(function() {
			self.setData({
				recording: false
			});
		});
	}
})
